package com.cecsmsserve.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cecsmsserve.entity.HealthRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Mapper
public interface HealthRecordMapper extends BaseMapper<HealthRecord> {
    
    @Select("SELECT hr.*, hrt.name as type_name, hrt.unit " +
            "FROM health_record hr " +
            "LEFT JOIN health_record_type hrt ON hr.type_id = hrt.id " +
            "WHERE hr.user_id = #{userId} " +
            "AND hr.type_id = #{typeId} " +
            "AND hr.record_date BETWEEN #{startDate} AND #{endDate} " +
            "ORDER BY hr.record_date ASC, hr.record_time ASC")
    List<HealthRecord> getRecordsByTypeAndDateRange(
            @Param("userId") Integer userId,
            @Param("typeId") Integer typeId,
            @Param("startDate") LocalDate startDate,
            @Param("endDate") LocalDate endDate);
    
    @Select("SELECT hr.*, hrt.name as type_name, hrt.unit, u.username as user_name " +
            "FROM health_record hr " +
            "LEFT JOIN health_record_type hrt ON hr.type_id = hrt.id " +
            "LEFT JOIN user u ON hr.user_id = u.id " +
            "WHERE hr.user_id = #{userId} " +
            "ORDER BY hr.record_date DESC, hr.record_time DESC")
    Page<HealthRecord> getRecordsByUserIdWithPage(
            Page<HealthRecord> page,
            @Param("userId") Integer userId);
    
    @Select("SELECT hrt.name as type_name, COUNT(hr.id) as record_count " +
            "FROM health_record hr " +
            "LEFT JOIN health_record_type hrt ON hr.type_id = hrt.id " +
            "WHERE hr.user_id = #{userId} " +
            "AND hr.record_date BETWEEN #{startDate} AND #{endDate} " +
            "GROUP BY hr.type_id")
    List<Map<String, Object>> getTypeStatistics(
            @Param("userId") Integer userId,
            @Param("startDate") LocalDate startDate,
            @Param("endDate") LocalDate endDate);
    
    @Select("SELECT COUNT(*) FROM health_record " +
            "WHERE user_id = #{userId} AND type_id = #{typeId} " +
            "AND record_date = #{recordDate}")
    Integer countByUserIdAndTypeIdAndDate(
            @Param("userId") Integer userId,
            @Param("typeId") Integer typeId,
            @Param("recordDate") LocalDate recordDate);
} 